package com.luban.springcloud.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

public class AuthFilter extends ZuulFilter{

	// 是否执行该过滤器，此处为true，说明需要过滤
	public boolean shouldFilter() {
		return true;
	}

	public Object run() throws ZuulException {
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		
		//获取token
		String token = request.getParameter("token");
		
		//这里只判断请求的url是否带token，带通过，反之
		if (StringUtils.isNotBlank(token)) {
			requestContext.setSendZuulResponse(true);
			requestContext.setResponseStatusCode(200);
			requestContext.set("code","ok");
		}else {
			requestContext.setSendZuulResponse(false);
			requestContext.setResponseStatusCode(401);
			HttpServletResponse response = requestContext.getResponse();
            response.setHeader("content-type", "text/html;charset=utf8");
            requestContext.setResponseBody("123luban鲁班编程学院温馨提示：路由网关认证失败，停止工作");
            requestContext.set("code", "fail");
		}
		return null;
	}

	//在请求被路由之前调用
	public String filterType() {
		return "pre";
	}

	// filter执行顺序，通过数字指定 ,优先级为0，数字越大，优先级越低
	public int filterOrder() {
		return 0;
	}

}
